<?php
class DBI{

	# $db_connection_count to be removed
  protected $db_connection_count =0 ;    # Members declared as private may only be accessed by the class that defines the member.
                                   # this counter count the number of connect & disconnect. it should be 1 or 0 if this application is properly written
                                   
  # to be removed                             
  protected $_DB_CONNECTION_POOL=array();
  
  protected $rw_mode;
  protected $app_dbname;
  protected $db_setting;
  private   $log_path ;
  
  protected $debug = 1;

  	
	# 
	# @param: rw_mode    : either 'read' | 'write'
	# @param: $app_dbname: the default db it connect to, as one mysql server probably have multiple DB,
	#                      pls don't user 'select * from dbname.tablename ' syntax in program
	# @param: $db_setting: 
	# 
	function __construct($rw_mode='read', $app_dbname='', $db_setting=array()){
		$rw_mode = $rw_mode != 'write' ? 'read' : 'write';
		$this->rw_mode    = $rw_mode;
		$this->app_dbname = $app_dbname;
		$this->db_setting = $db_setting;
		
		
	} # end construct
	
	function connect(){

		global $site_global_config;
		global $db_config;

		if ($this->debug > 0){
			$this->log_path = $site_global_config['LOG'];
		}  
		
		$rw_mode    = $this->rw_mode    ;
		$app_dbname = $this->app_dbname ;
		$db_setting = $this->db_setting ;
		
		$temp = $db_setting; # copy array
		
		array_unshift($temp, $rw_mode, $app_dbname);
		$db_cache_key = implode('.', $temp); # create a caching identifier
   		
		if (isset($this->_DB_CONNECTION_POOL[$db_cache_key])){
			
			if ($this->debug > 0){
			  $this->log_error('db_class','DB Connect through cached dbh: '.$db_cache_key);
		  }
			return $this->_DB_CONNECTION_POOL[$db_cache_key]; # cached db connection
		} 
    # no same connection (within the same process) is available
    #  -- pls note, note  NOT talking about persistent connection
    
    
    
    
		if (empty($db_setting)){
			/*$db_setting = $rw_mode == 'read' ? $site_global_config['DBRead']
			                                 : $site_global_config['DBWrite'] ;*/
			$db_tmp = $db_config['DB_'.$rw_mode];
			$db_setting = array($db_tmp['dbhost'],$db_tmp['dbname'],$db_tmp['username'],$db_tmp['password'],$db_tmp['pconnect']);
		}
		
		# 
		list ($db_host, $dbname, $dbuser, $dbpasswd, $persistent) = $db_setting;
		
    if (! empty_string($app_dbname) && $app_dbname !== $dbname  ){ // $app_dbname ne '' and $app_db_name ne $dbname
    	$dbname = $app_dbname;
    }

		// ??? dbh caching - php run as cgi (dynamic structure?), caching of dbh should depends on db name
		//$dsn = 'mysql:unix_socket=/xampp/mysql/mysql.sock;dbname=cms';
	  $dsn  = "mysql:host=$db_host;dbname=$dbname;";

    ////If you use the UTF-8 encoding, you have to use the fourth parameter :
    //$db = new PDO('mysql:host=myhost;dbname=mydb', 'login', 'password', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));

    try {
    	$h_param = array(
    	  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION 
    	);
    	if ($persistent){

    		if ($this->debug > 0){
    			$this->log_error('db_class','use persistent DB connect.');
    		}
    		$h_param[PDO::ATTR_PERSISTENT] = true;
    	}
    	// note: no select_db in mysql modlues
    	$this->db_connection_count++;
      $this->_DB_CONNECTION_POOL[$db_cache_key] = new PDO($dsn, $dbuser, $dbpasswd, $h_param);
       # $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    } catch (PDOException $e) {
      //$this->db_connection_count--; // not probably connected, don not count down...
      throw new ErrorException('Unable to connect to db server. Error:'.$e->getMessage(), 31);
    }
		
    return $this->_DB_CONNECTION_POOL[$db_cache_key];		


  } # end connect 
  
  
  
	
	
	function disconnect(){
 	  foreach ($this->_DB_CONNECTION_POOL as $k => $v){
      $this->db_connection_count--;            
      $this->_DB_CONNECTION_POOL[$k] = null; // need to test it...
  	}
	}
	
	
	
  function log_error($name, $msg){
    $now = date("m-d-y H:i:s");
    $path = $this->log_path.$name.'.log';
    #echo "$now\t$msg\n";
    AppendFile($path, "$now\t$msg\n");
  }
  
  
  
  ###########################################################################


  
  
  
  
  
  
}
?>